package com.wushi.lenovo.asia5b.app_ui.other.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.chrisbanes.photoview.PhotoView;
import com.mvp.base.BaseAppCompatActivity;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;
import com.wushi.lenovo.asia5b.app_utils.helper.UriHelper;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/5/6.
 * 查看PDF文档
 */
public class PdfPreviewActivity extends BaseAppCompatActivity {//
    @BindView(R.id.tv_title_titletext)
    TextView tv_title_titletext;
    @BindView(R.id.iv_title_more)
    ImageView iv_title_more;
    @BindView(R.id.iv_pdf_img)
    PhotoView mImageView;
    @BindView(R.id.tv_title_left_back)
    TextView tv_title_left_back;
    @BindView(R.id.tv_pdf_leftpage)
    TextView tv_pdf_leftpage;
    @BindView(R.id.tv_pdf_rightpage)
    TextView tv_pdf_rightpage;
    private PopupWindow popupWindow;
    private int mPageIndex = 0;//当前页角标
    private PdfRenderer.Page mCurrentPage;
    private PdfRenderer mPdfRenderer;
    private ParcelFileDescriptor mFileDescriptor;
    String pdfFilePath = null;
    String pdfOrderNo = null;

    public static void startPdfPreviewActivity(Context context, String pdfFilePath, String pdfOrderNo) {
        Intent intent = new Intent(context, PdfPreviewActivity.class);
        intent.putExtra(CommonConstant.PREVIEW_PDF_FILEPATH, pdfFilePath);
        intent.putExtra(CommonConstant.PREVIEW_PDF_ORDERNO, pdfOrderNo);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pdfpreview;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pdfFilePath = getIntent().getStringExtra(CommonConstant.PREVIEW_PDF_FILEPATH);
//        pdfFilePath="/storage/emulated/0/asia5bnew/pdf/sample.pdf";
        pdfOrderNo = getIntent().getStringExtra(CommonConstant.PREVIEW_PDF_ORDERNO);
        if (!TextUtils.isEmpty(pdfOrderNo)) {
            tv_title_titletext.setText(pdfOrderNo);
        }
        if (TextUtils.isEmpty(pdfFilePath)) {
            pdfFilePath = "";
        }
        d(format("--->>>>>>>>---pdfFilePath:%s", pdfFilePath));
        initView();
        initEvent();
    }


    private void openRenderer() throws IOException {
        mFileDescriptor = ParcelFileDescriptor.open(new File(pdfFilePath), ParcelFileDescriptor.MODE_READ_ONLY);
        // This is the PdfRenderer we use to render the PDF.
        if (mFileDescriptor != null) {
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        }
    }

    private void closeRenderer() throws IOException {
        if (null != mCurrentPage) {
            mCurrentPage.close();
        }
        mPdfRenderer.close();
        mFileDescriptor.close();
    }

    private void showPage(int index) {
        try {
            if (mPdfRenderer.getPageCount() <= index) {
                return;
            }
            if (null != mCurrentPage) {
                mCurrentPage.close();
            }
            mCurrentPage = mPdfRenderer.openPage(index);
            Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth() * 4, mCurrentPage.getHeight() * 4,
                    Bitmap.Config.ARGB_8888);
            Timber.d(format("--->>>>>>>>---图片大小:%d,width:%d,height:%d", bitmap.getByteCount(), mCurrentPage.getWidth(), mCurrentPage.getHeight()));
            mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            mImageView.setImageBitmap(bitmap);
        } catch (Throwable e) {//如果报空指针异常或者内存溢出,用第三方软件打开
            CrashHelper.postCatchedException(e);
            ToastUtil.showToast(getString(R.string.pdf_preview_notice2));
            File file = new File(pdfFilePath);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(UriHelper.getUri(file), "application/pdf");
            startActivity(intent);
        }
        updateUi();
    }

    private void updateUi() {
        int index = mCurrentPage.getIndex();
        int pageCount = mPdfRenderer.getPageCount();
        tv_pdf_leftpage.setVisibility(index == 0 ? View.GONE : View.VISIBLE);
        tv_pdf_rightpage.setVisibility((pageCount == (index + 1)) ? View.GONE : View.VISIBLE);
    }

    @Override
    protected void initView() {
        initWindow();
        try {
            openRenderer();
            showPage(mPageIndex);
        } catch (IOException e) {
            CrashHelper.postCatchedException(e);
        }
    }

    private void initWindow() {
        View popupView = View.inflate(this, R.layout.popup_pdf, null);
        popupView.setOnClickListener(v -> {
            try {
                File file = new File(pdfFilePath);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(UriHelper.getUri(file), "application/pdf");
                startActivity(intent);
            } catch (Exception e) {
                CrashHelper.postCatchedException(e);
            }
            popupWindow.dismiss();
        });
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
    }

    @OnClick({
            R.id.iv_title_more,
            R.id.tv_pdf_rightpage,
            R.id.tv_pdf_leftpage
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_more:
                try {
                    popupWindow.setFocusable(true);
                    popupWindow.update();
                    popupWindow.showAsDropDown(v);
                } catch (Exception e) {
                    CrashHelper.postCatchedException(e);
                }
                break;
            case R.id.tv_pdf_rightpage://下一页
                showPage(mCurrentPage.getIndex() + 1);
                break;
            case R.id.tv_pdf_leftpage://上一页
                showPage(mCurrentPage.getIndex() - 1);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        try {
            closeRenderer();
        } catch (Throwable e) {
            CrashHelper.postCatchedException(e);
        }
        super.onDestroy();
    }
}
